package com.hxzy.controller.admin.dashboard.strategy;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.unit.DataUnit;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hxzy.common.constans.RedisConstans;
import com.hxzy.controller.admin.dashboard.resp.ReportResp;
import com.hxzy.entity.Contamer;
import com.hxzy.service.ContamerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.xml.crypto.Data;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Author wy
 * @Description 本月
 * @Date 2023/7/17 10:28
 * @Version 1.0
 */
@Component
public class CurrentMonthReport implements ContamerReportStrategy {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ContamerService contamerService;


    @Override
    public ReportResp calcReport() {

        int year= DateUtil.year(new Date());
        int month=DateUtil.month(new Date())+1;

        List<String> xAxis=new ArrayList<>();
        List<Object> series=new ArrayList<>();

        //开始日期
        Date beginDate= DateUtil.beginOfMonth(new Date());
        //结束日期
        Date endDate=  new Date() ;
        //开始天数
        int beginDay= DateUtil.dayOfMonth(beginDate);
        //结束天数
        int endDay=DateUtil.dayOfMonth(endDate);

        //构造redisKey
        String ym=year+""+((month<10)?"0"+month: month);
        String redisKey= RedisConstans.getRedisKey(RedisConstans.CONTAMER_HASH_KEY,ym);


        Map<String,Integer> entries = this.redisTemplate.opsForHash().entries(redisKey);

        for(int i=beginDay;i< endDay;i++){

            if(i ==1) {
                xAxis.add(month+"/"+i);
            }else{
                xAxis.add(i+"");
            }
            Integer integer = entries.get(i + "");
            if(integer!=null){
                series.add(integer);
            }else{
                series.add(0);
            }
        }

        //查询今天的数据(从数据库中查询出来)
        Date todayBegin=DateUtil.beginOfDay(new Date());
        Date todayEnd=DateUtil.endOfDay(new Date());

        LambdaQueryWrapper<Contamer> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.between(Contamer::getCreateTime, todayBegin,todayEnd);
        long count = this.contamerService.count(queryWrapper);

        xAxis.add(endDay+"");
        series.add(count);


        ReportResp  reportResp=new ReportResp();
        reportResp.setXAxis(xAxis);
        reportResp.setSeries(series);
        return reportResp;
    }
}
